<!--教师管理-->
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="姓名" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:test:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:test:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:test:remove']"
          >删除</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:user:import']"
          >导入教师账号</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport2"
          v-hasPermi="['system:user:import']"
          >导入教学信息</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:test:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="testList"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="序号" align="center" prop="userId" />
      <el-table-column label="姓名" align="center" prop="nickName" />
      <el-table-column
        label="性别"
        align="center"
        prop="sex"
        :formatter="formatSex"
      />
      <el-table-column label="教学科目" align="center" prop="mapSubject" />
      <el-table-column
        label="是否班主任"
        align="center"
        prop="headTeacher"
        :formatter="formatheadteacher"
      />
      <el-table-column label="管理班级" align="center" prop="gradeNameList" />
      <el-table-column label="联系电话" align="center" prop="phonenumber" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:test:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:test:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="950px" append-to-body>
      <!-- 教师信息 -->
      <div class="Teacherinformation">
        <span class="fl red"></span>
        <span class="fl">教师信息</span>
      </div>
      <el-form
        class="fr"
        :inline="true"
        ref="form"
        :model="form"
        :rules="rules"
        label-width="85px"
      >
        <el-form-item label="姓名" prop="nickName">
          <el-input
            v-model="form.nickName"
            placeholder="请输入姓名"
            style="width: 350px"
            clearable
          />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select
            v-model="form.sex"
            placeholder="请选择性别"
            style="width: 350px"
          >
            <el-option label="男" value="0"></el-option>
            <el-option label="女" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phonenumber">
          <el-input
            v-model="form.phonenumber"
            placeholder="请输入联系电话"
            style="width: 350px"
            clearable
          />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-show="ispassword">
          <el-input
            v-model="form.password"
            placeholder="请输入密码"
            style="width: 350px"
          />
        </el-form-item>
      </el-form>
      <!-- 新增岗位 -->
      <div class="Teacherinformation">
        <span class="fl red"></span>
        <span class="fl">教学信息</span>
        <i class="iconfont icon-xinzeng" @click="addpost">添加岗位</i>
      </div>
      <!-- 添加岗位 -->
      <el-form
        ref="form"
        :model="form"
        :inline="true"
        :rules="rules"
        label-width="85px"
      >
        <div v-for="(item,index) in form.teachingInfo" :key="index">
        <el-form-item label="教师岗位" :prop="'teachingInfo.'+index+'.post'">
          <el-select
            v-model="item.post"
            placeholder="请选择岗位"
            style="width: 170px"
          >
            <el-option label="班主任" value="班主任"></el-option>
            <el-option label="任课老师" value="任课老师"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教学科目" :prop="'teachingInfo.'+index+'.literarycourse'">
          <el-select
            v-model="item.literarycourse"
            placeholder="请选择教学科目"
            style="width: 170px"
          >
            <el-option
              v-for="(subject, index) in subjectlist"
              :key="index"
              :label="subject.subjectName"
              :value="subject.subjectName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任课班级" :prop="'teachingInfo.'+index +'.teacherclass'">
          <el-cascader
            v-model="item.teacherclass"
            placeholder="请选择任课班级"
            filterable
            :options="options"
            :show-all-levels="false"
            style="width: 170px"
          ></el-cascader>
        </el-form-item>
        <el-form-item>
          <span
            class="iconfont icon-jianshao"
            @click="deletepost(item, index)"
            style="color:#9c0000"
            >删除岗位</span>
        </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入教师账号对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载教师账号模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm1">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入教学信息对话框 -->
    <el-dialog
      :title="upload2.title"
      :visible.sync="upload2.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload2"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload2.headers"
        :action="upload2.url + '?updateSupport=' + upload2.updateSupport"
        :disabled="upload2.isUploading"
        :on-progress="handleFileUploadProgress2"
        :on-success="handleFileSuccess2"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload2.updateSupport" />
            是否更新已经存在的用户数据upload
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate2"
            >下载教学信息模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload2.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getteacherlist,
  getdelteacher,
  getTeacherManages,
  getclasslist,
  getGrade,
  getaddteacher,
  getexitteacher,
  getchangeteacher,
} from "@/api/teacher";
import { getToken } from "@/utils/auth";
export default {
  name: "Test",
  data() {
    return {
      //默认表单密码显示
      ispassword:true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      testList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: null,
        // sex: null,
        // mapSubject: null,
        // headTeacher: null,
        // gradeNameList: null,
        // phonenumber: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 存放所有学科的数据
      subjectlist: [],
      // 存放年级班级数据
      options: [],
      //存放处理后的岗位信息
      teacherpostarr:[],
       //回显教师数据
      data: {},
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/business/teacherManage/importTeacherAccount",
      },
      upload2: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/business/teacherManage/import",
      },
    };
  },
  created() {
    //调用列表数据的回调
    this.getList();
    //调用所有学科的回调
    this.classlist();
    //调用年级班级回调
    this.Grade();
  },
  methods: {
    //表格中性别数据处理
    formatSex(row, column, cellValue) {
      if (cellValue === "1") {
        return "女";
      } else if (cellValue === "0") {
        return "男";
      }
    },
    //表格中是否班主任数据处理
    formatheadteacher(row, column, cellValue) {
      if (cellValue === "0" || cellValue === null) {
        return "否";
      } else if (cellValue === "1") {
        return "是";
      }
    },
    //教学科目
    async classlist() {
      let result = await getclasslist();
      if (result.code == 200) {
        this.subjectlist = result.rows;
      }
    },
    //获取年级班级数据
    Grade() {
      getGrade(this.queryParams).then((response) => {
        this.options = Object.keys(response).map((key) => {
          let obj = {
            value: key,
            label: key,
            children: response[key].map((childKey) => ({
              value: childKey,
              label: childKey,
            })),
          };
          return obj;
        });
        // console.log('666',this.options)
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      getteacherlist(this.queryParams).then((response) => {
        this.testList = response.rows;
        this.total = response.total;
        this.loading = false;
        for (const x in this.testList) {
          this.subject = Object.keys(this.testList[x].mapSubject).join(",");
          this.testList[x].mapSubject = this.subject;
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId:"",
        nickName: "",
        phonenumber: "",
        sex: "",
        password: "",
        //存放教学信息的数据
        teachingInfo: [],
      };
      this.resetForm("form");
    },
    // 添加岗位
    addpost() {
      this.form.teachingInfo.push({
        //教师岗位
        post: "",
        //教学科目
        literarycourse: "",
        //任课班级
        teacherclass: "",
      });
    },
    //删除岗位
    deletepost(item, index) {
      this.form.teachingInfo.splice(index, 1);
    },
    /** 搜索按钮操作 */
    async handleQuery() {
      if (this.queryParams.nickName != "") {
        
        const result = await getTeacherManages(this.queryParams.nickName);
        this.testList = result.rows;
        this.total = result.total;
        for (const x in this.testList) {
          this.subject = Object.keys(this.testList[x].mapSubject).join(",");
          this.testList[x].mapSubject = this.subject;
        }
      } else {
        this.getList();
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.getList();
    },
    // 多选框选中数据
    // handleSelectionChange(selection) {
    //   this.ids = selection.map((item) => item.userId);
    //   this.single = selection.length !== 1;
    //   this.multiple = !selection.length;
    // },
    /** 新增按钮操作 */
    handleAdd() {
      this.ispassword=true;
      this.reset();
      this.open = true;
      this.title = "新增教师记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.ispassword=false;
      this.reset();
      this.form.userId = row.userId || this.ids;
      getexitteacher( this.form.userId ).then((response) => {
        this.data = response;
          //页面回显
          this.form.nickName = this.data.nickName;
          this.form.phonenumber = this.data.phonenumber;
          this.form.sex = this.data.sex;
          for (const x in this.data.teachingInfo) {
            let data = this.data.teachingInfo[x].split(":");
            this.form.teachingInfo.push({
              post: data[0],
              literarycourse: data[1],
              teacherclass: data[2]-0
            });
          }
        this.open = true;
        this.title = "修改教师记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 修改
          if (this.form.userId != "") {
            this.teacherpostarr=[];
            for(const x in this.form.teachingInfo){
              if(typeof(this.form.teachingInfo[x].teacherclass)==="number"){
                this.teacherpostarr.push(this.form.teachingInfo[x].post+":"+this.form.teachingInfo[x].literarycourse+":"+this.form.teachingInfo[x].teacherclass)
              }else{
                this.teacherpostarr.push(this.form.teachingInfo[x].post+":"+this.form.teachingInfo[x].literarycourse+":"+this.form.teachingInfo[x].teacherclass[1])
              }
            }
            getchangeteacher({
              userId:this.form.userId,
              nickName:this.form.nickName,
              sex:this.form.sex,
              phonenumber:this.form.phonenumber,
              teachingInfo:this.teacherpostarr
            }).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 新增
            this.teacherpostarr=[];
            for(const x in this.form.teachingInfo){
              this.teacherpostarr.push(this.form.teachingInfo[x].post+":"+this.form.teachingInfo[x].literarycourse+":"+this.form.teachingInfo[x].teacherclass[1])
            }
            getaddteacher({
              nickName:this.form.nickName,
              sex:this.form.sex,
              password:this.form.password,
              phonenumber:this.form.phonenumber,
              teachingInfo:this.teacherpostarr
            }).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal
        .confirm('是否确认删除序号为"' + userIds + '"的数据项？')
        .then(function () {
          return getdelteacher(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出教师列表按钮操作 */
    handleExport() {
      this.download(
        "business/teacherManage/export",
        {
          ...this.queryParams,
        },
        `teacher_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入教师账号按钮操作 */
    handleImport() {
      this.upload.title = "教师账号导入";
      this.upload.open = true;
    },
    /** 下载教师账号模板操作 */
    importTemplate() {
      this.download(
        "/business/teacherManage/exportTeacherModel",
        {},
        `teacheraccount_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm1() {
      console.log('111')
      this.$refs.upload.submit();
    },
     /** 导入教学信息按钮操作 */
    handleImport2() {
      this.upload2.title = "教学信息导入";
      this.upload2.open = true;
    },
    /** 下载教学信息模板操作 */
    importTemplate2() {
      this.download(
        "/business/teacherManage/exportTeacherManageModel",
        {},
        `teachinginformation_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress2(event, file, fileList) {
      this.upload2.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess2(response, file, fileList) {
      this.upload2.open = false;
      this.upload2.isUploading = false;
      this.$refs.upload2.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload2.submit();
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss">
// 教师信息 教学信息
.Teacherinformation {
  padding-bottom: 3.125rem;
  .red {
    width: 0.375rem;
    height: 1.6875rem;
    background: #9c0000;
    margin-right: 0.625rem;
  }
  // 编辑教师
  i {
    margin-left: 0.625rem;
    color: #9c0000;
  }
}

.el-dialog__body {
  height: calc(100% - 150px);
}
</style>